package com.zego.wawaji.ui.center.wawa;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.zego.wawaji.R;
import com.zego.wawaji.base.module.ModuleMgr;
import com.noble.library.observer.MsgMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.noble.library.observer.PObserver;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.http.request.HttpResponse;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.http.request.UrlParam;
import com.zego.wawaji.ui.UIShow;
import com.zego.wawaji.ui.base.BasePanel;
import com.zego.wawaji.ui.base.CustomRecyclerView;
import com.zego.wawaji.ui.base.xlistview.ExListView;
import com.zego.wawaji.ui.bean.wawa.MyWawa;
import com.zego.wawaji.ui.bean.wawa.MyWawaList;
import com.zego.wawaji.ui.bean.wawa.WawaConstant;
import com.zego.wawaji.ui.dialog.PickerDialogUtil;
import com.zego.wawaji.ui.dialog.SimpleTipDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的娃娃：寄存中
 * Created by Su on 2017/11/26.
 */
public class MyWawaUntreated extends BasePanel implements PObserver, RequestComplete, ExListView.IXListViewListener, View.OnClickListener {
    private CustomRecyclerView statusLayout;
    private ExListView exListView;
    private int page = 1; // 加载页码

    private UntreatedAdapter adapter;
    private List<MyWawa> list = new ArrayList<>();

    public MyWawaUntreated(Context context) {
        super(context);
        setContentView(R.layout.my_wawa_untreated);
        initView();
        onRefresh();
    }

    private void initView() {
        MsgMgr.getInstance().attach(this);
        statusLayout = (CustomRecyclerView) findViewById(R.id.statusLayout);
        View mViewTop = LayoutInflater.from(getContext()).inflate(R.layout.layout_margintop, null);
        exListView = statusLayout.getExListView();
        exListView.setXListViewListener(this);
        exListView.setPullRefreshEnable(true);
        exListView.setPullLoadEnable(false);
        exListView.addHeaderView(mViewTop);
        adapter = new UntreatedAdapter(getContext(), list);
        exListView.setAdapter(adapter);
        statusLayout.showLoading();

        findViewById(R.id.send_all).setOnClickListener(this);
        findViewById(R.id.synth_wawa).setOnClickListener(this);
    }

    @Override
    public void onRefresh() {
        exListView.setPullRefreshEnable(true);
        page = 1;
        ModuleMgr.getWawaMgr().reqMyWawa(WawaConstant.WAWA_NO_SEND, page, this);
    }

    @Override
    public void onLoadMore() {
        page++;
        ModuleMgr.getWawaMgr().reqMyWawa(WawaConstant.WAWA_NO_SEND, page, this);
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        exListView.stopRefresh();
        exListView.stopLoadMore();
        if (response.getUrlParam() == UrlParam.reqMyWawa) {
            setData(response);
        }
    }

    private void setData(HttpResponse response) {
        // 请求失败
        if (!response.isOk()) {
            if (list.size() != 0) {
                adapter.notifyDataSetChanged();
                statusLayout.showExListView();
                return;
            }
            statusLayout.showNoData("没有寄存中的娃娃", "立即去抓", view -> MsgMgr.getInstance().sendMsg(MsgType.MT_Jump_PlayFragment, null));
            return;
        }

        MyWawaList myWawaList = (MyWawaList) response.getBaseData();
        List<MyWawa> wawaList = myWawaList.getMyWawaUntreatedList();

        if (wawaList.size() != 0) {
            list.clear();
            list.addAll(wawaList);

            if (refreshType == 1) {  // 全选
                refreshChooseStatus(refreshType);
            } else {
                adapter.reset();
            }

            adapter.notifyDataSetChanged();
            statusLayout.showExListView();
        } else {
            statusLayout.showNoData("没有寄存中的娃娃", "立即去抓", view -> MsgMgr.getInstance().sendMsg(MsgType.MT_Jump_PlayFragment, null));
        }
    }

    public void release() {
        MsgMgr.getInstance().detach(this);
    }

    /**
     * 刷新首页
     */
    public void refreshList() {
        onRefresh();
        if (adapter != null && adapter.getList() != null && adapter.getList().size() != 0) {
            exListView.setSelection(0);
        }
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Wawa_Untreated:
                if (adapter != null)
                    adapter.reset();
                refreshList();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_all:
                sendAll();
                break;
            case R.id.synth_wawa:
                UIShow.showSynthWawaActivity(getActivity());
                break;
        }
    }

    private void sendAll() {
        if (list == null || list.size() <= 0) {
            PToast.showShort("您还没有寄存中的娃娃！");
            return;
        }

        if (adapter == null || adapter.getChooseList().size() <= 0) {
            PToast.showShort("您还没有选择娃娃！");
            return;
        }
        int size = adapter.getChooseList().size();
        long[] ids = new long[size];

        for (int i = 0; i < size; i++) {
            ids[i] = adapter.getChooseList().get(i).getId();
        }
        final String strIds = JSON.toJSONString(ids);

        // 判断是否有大娃娃
        String freeSendBigNum = ModuleMgr.getWawaMgr().getCommon().getFreeSendBigWwMin();
        String bigNum = TextUtils.isEmpty(freeSendBigNum) ? "0" : freeSendBigNum;
        boolean hasBig = adapter.getBigWawaList().size() > Integer.valueOf(bigNum);
        if (hasBig) {
            UIShow.showMyAddressAct(getActivity(), 1, strIds);
            return;
        }

        String freeSendNum = ModuleMgr.getWawaMgr().getCommon().getFreeSendWwMin();
        String sendWwCoin = ModuleMgr.getWawaMgr().getCommon().getRequsetSendWwCoinMin();
        String num = TextUtils.isEmpty(freeSendNum) ? "4" : freeSendNum;
        String coinNum = TextUtils.isEmpty(sendWwCoin) ? "80" : sendWwCoin;
        if (size < Integer.valueOf(num)) {
            String content = "限时活动满" + num + "件包邮，低于" + num + "件收取" + coinNum + "金币运费哦！";
            PickerDialogUtil.showSimpleTipDialogExt((FragmentActivity) getActivity(), new SimpleTipDialog.ConfirmListener() {
                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onSubmit() {
                            UIShow.showMyAddressAct(getActivity(), 1, strIds);
                        }
                    }, content, "温馨提示", "取消", "确认发货",
                    true, R.color.text_gray);
            return;
        }

        UIShow.showMyAddressAct(getActivity(), 1, strIds);
    }

    // ==================================== 全选/取消全选 =================================
    private int refreshType = 0;        // 0: 默认常规刷新  1： 全选刷新  2： 取消全选刷新

    public void resetRefreshType(int refreshType) {
        this.refreshType = refreshType;
    }

    /**
     * 列表刷新
     */
    public void refreshChooseStatus(int refreshType) {
        this.refreshType = refreshType;
        adapter.setRefreshType(refreshType);
        adapter.notifyDataSetChanged();
    }
}
